<template>
  <div>

    <el-container>
      <el-header>
        <h1>价格为:<b style="color: red">{{ price }}元</b></h1>
      </el-header>
      <el-main>
        <div id="qrcode"></div>
      </el-main>
    </el-container>


  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import order from '@/api/order/order'

export default {
  name: 'pay',
  data() {
    return {
      payData: {},//订单数据
      orderId: '',//订单id
      price: '',//价格
      timeout: '',//定时器
      timeMills: ''//时间戳,用来作为订单号
    }
  },
  components: { QRCode },
  methods: {
    //  生成二维码
    qrcode() {
      let that = this
      let qrcode = new QRCode('qrcode', {
        width: 300,
        height: 300,        // 高度
        text: this.payData.data.code_url   // 二维码内容
        // render: 'canvas' ,   // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        // background: '#f0f',   // 背景色
        // foreground: '#ff0'    // 前景色
      })
    },
    /**
     * 申请微信支付地址
     */
    createPay() {
      order.createPay(this.orderId, this.timeMills).then(data => {
        this.payData = data
        this.price = this.payData.data.total_fee
        this.$nextTick(function() {
          this.qrcode()
        })
      })
    }, queryOrderStatus(id,timeMills) {
      order.queryOrderStatus(id,timeMills).then(data => {
        console.log('支付状态为:', data)
        if (Number(data.code) == 2003) {
          window.clearInterval(this.timeout)
          console.log('定时器清除成功!')
          this.$message({
            type: 'success',
            message: '支付成功!',
            showClose: true
          })
          this.$router.push({ path: '/order/orderInfo' })
        }
      }).catch(e => {
        window.clearInterval(this.timeout)
      })
    }
  }, created() {

    if (this.$route.params && this.$route.params.id) {
      this.orderId = this.$route.params.id
      this.timeMills = new Date().getTime()
      this.createPay()
    }
  }, mounted() {
    /**
     *页面渲染之后执行,每隔三秒查询一次订单状态
     * @type {number}
     */
    if (this.payData) {
      this.timeout = setInterval(() => {
        this.queryOrderStatus(this.$route.params.id, this.timeMills)
      }, 3000)
    }

  }
}
</script>

<style scoped>

</style>
